package com.lej.core.base

import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.lej.core.bus.event.SingleLiveEvent
import java.lang.ref.WeakReference

open class BaseViewModel<M : BaseModel?> : ViewModel, IBaseViewModel {
    protected var model: M? = null
    private var uc: UIChangeLiveData? = null
    //弱引用持有
    private var lifecycle: WeakReference<LifecycleOwner>? = null

    constructor()

    constructor(model: M) {
        this.model = model
    }

    /**
     * 注入RxLifecycle生命周期
     */
    fun injectLifecycleProvider(lifecycle: LifecycleOwner) {
        this.lifecycle = WeakReference(lifecycle)
    }

    val lifecycleProvider: LifecycleOwner?
        get() = lifecycle?.get()

    val uC: UIChangeLiveData
        get() {
            if (uc == null) uc = UIChangeLiveData()
            return uc!!
        }

    @JvmOverloads
    fun showDialog(title: String = "请稍后...") {
        uC.showDialogEvent?.postValue(title)
    }

    fun dismissDialog() {
        uC.dismissDialogEvent?.call()
    }

    /**
     * 关闭界面
     */
    fun finish() {
        uC.finishEvent?.call()
    }

    /**
     * 返回上一层
     */
    fun onBack(view: View?) {
        uC.onBackPressedEvent?.call()
    }

    override fun onAny(owner: LifecycleOwner?, event: Lifecycle.Event?) {}

    override fun onCreate() {}
    override fun onDestroy() {}
    override fun onStart() {}
    override fun onStop() {}
    override fun onResume() {}
    override fun onPause() {}

    override fun onCleared() {
        super.onCleared()
        model?.onCleared()
    }

    class UIChangeLiveData : SingleLiveEvent<Any?>() {
        var showDialogEvent: SingleLiveEvent<String>? = null
            get() = createLiveData(field).also { field = it }
            private set
        var dismissDialogEvent: SingleLiveEvent<Void>? = null
            get() = createLiveData(field).also { field = it }
            private set

        var finishEvent: SingleLiveEvent<Void>? = null
            get() = createLiveData(field).also { field = it }
            private set

        var onBackPressedEvent: SingleLiveEvent<Void>? = null
            get() = createLiveData(field).also { field = it }
            private set

        private fun <T> createLiveData(liveData: SingleLiveEvent<T>?) =
            liveData ?: SingleLiveEvent()
    }
}